package com.zr.task.activity;


import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.zh.baselibrary.base.CountTimeBaseActivity;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.task.error.ErrorDetailBean;
import com.zh.model.task.error.ErrorDetailVOBean;
import com.zh.model.task.error.ErrorStuInfoBean;
import com.zr.andealib.util.HardEvent;
import com.zr.andealib.util.constant.AndeaConstant;
import com.zr.task.R;
import com.zr.task.adapter.CorrigedumDetailAdapter;
import com.zr.task.constant.Constant;
import com.zr.task.presenter.CorrigedumPresenter;
import com.zr.task.presenter.view.CorrigendumDetailView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 勘误详情界面
 */
public class CorrigendumDetailActivity extends CountTimeBaseActivity<CorrigedumPresenter> implements CorrigendumDetailView {


    @BindView(R.id.tv_notice)
    TextView mTvNotice;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.rv_ralation)
    RecyclerView mRvRalation;
    @BindView(R.id.rl_title)
    RelativeLayout titleRelative;
    public static final int RELATION_HOMEWORK_CODE = 10000;
    public static final int RESULT_CODE_COMPLTE = 10001;
    private boolean isOpen = false;
    CorrigedumDetailAdapter mAdapter;
    ErrorDetailVOBean mBean;
    List<ErrorStuInfoBean> list = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_corrigendum_detail;
    }

    @Override
    public void timeFinish() {
        super.timeFinish();
        if (isOpen) {
            mPresenter.complte(mBean);
        } else {
            setResult(RELATION_HOMEWORK_CODE);
            finish();
        }

    }
    @Override
    protected void init() {
        mBean = (ErrorDetailVOBean) getIntent().getSerializableExtra(ExtraName.KEY_DATA);
        int color = getIntent().getIntExtra(ExtraName.KEY_COLOR,0);
        if(color!=0)
            titleRelative.setBackgroundColor(color);
        mAdapter = new CorrigedumDetailAdapter(list);
        mRvRalation.setLayoutManager(new LinearLayoutManager(this));
        mRvRalation.setAdapter(mAdapter);
        mPresenter.getErrorDetail(mBean);
        EventBus.getDefault().register(this);
    }
    @OnClick({R.id.iv_back, R.id.tv_submit})
    public void onViewClicked(View view) {
       if(view.getId() == R.id.iv_back){
           if (isOpen) {
               ToastView.showLong("当前柜门未关闭，请关闭柜门再操作");
           } else {
               finish();
           }
       }else {
           if (mAdapter.getItemCount() == 0) {
               ToastView.showLong("当前无勘误记录");
               setResult(RESULT_CODE_TIME_FINISH);
               return;
           }
           if (!isOpen) {
               mPresenter.openDoor(mBean);
               isOpen = true;
               Set<String> set = new HashSet<>();
               for (ErrorStuInfoBean errorStuInfoBean : list) {
                   set.add(errorStuInfoBean.getRadioCode());
               }
               Intent mIntent = new Intent();
               mIntent.setAction(Constant.BROAT_CAST_ACTION_ERROR_COMPLTE);
               mIntent.putExtra(ExtraName.KEY_DATA, (Serializable) set);
               mIntent.putExtra(ExtraName.KEY_TRAN_DATA, mBean.getCabinetNum());
               sendBroadcast(mIntent);
           } else {
               ToastView.showLong("柜门已开启");
           }
       }
    }
    @Override
    protected CorrigedumPresenter createPresenter() {
        return new CorrigedumPresenter();
    }

    @Override
    public void detailSuccess(ErrorDetailBean mErrorDetailBean) {
        if (mErrorDetailBean.getCount() == 0) {
            ToastView.showLong("当前科目无误投记录");
            TTSUtils.getInstance().speak(getString(R.string.no_error));
            finish();
        }
        mTvName.setText("您好，" + mErrorDetailBean.getStudentName());
        mTvNotice.setText("请对照上方误投明细，取出所有误投的作业，共计：" + mErrorDetailBean.getCount() + "本");
        mAdapter.addData(mErrorDetailBean.getMiscarriageStuVOS());
    }
    @Subscribe(priority = 1000,threadMode = ThreadMode.POSTING)
    public void Event(HardEvent hardEvent) {
        int flag = hardEvent.getFlag();
        if (flag == AndeaConstant.CALL_LOCK_STATUS_SUCCSES) {
            TTSUtils.getInstance().speak(getString(R.string.take_error));
            mPresenter.openSuccess();
            EventBus.getDefault().cancelEventDelivery(hardEvent) ;
        }else if(flag == AndeaConstant.CALL_LOCK_STATUS_ERROR ){
            String tip = (String)hardEvent.getData();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastView.showLong(tip);
                }
            });
            if(!tip.equals("柜门处于开启状态")) {
                TTSUtils.getInstance().speak(getString(R.string.can_not_open));
            }
            EventBus.getDefault().cancelEventDelivery(hardEvent) ;
        }
    }
    @Override
    public void detailError(String error) {
        ToastView.showLong(error);
    }

    @Override
    public void complteError(String error) {
        ToastView.showLong(error);
        isOpen = false;
        finish();
    }

    @Override
    public void complteSuccess() {
        Set<String> set = new HashSet<>();
        for (ErrorStuInfoBean errorStuInfoBean : list) {
            set.add(errorStuInfoBean.getRadioCode());
        }
        isOpen = false;
        Intent mIntent = new Intent();
        mIntent.putExtra(ExtraName.KEY_DATA, (Serializable) set);
        mIntent.putExtra(ExtraName.KEY_TRAN_DATA, mBean.getCabinetNum());
        setResult(RESULT_CODE_COMPLTE, mIntent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
